import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from '../store'

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login'),
    meta: {
      title: '登录',
      requireAuth: false,//添加该字段，表示进入路由是否需要登录
    },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../components/404'),
    meta: {
      title: '404',
      requireAuth: false,//添加该字段，表示进入路由是否需要登录
    },
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/Workdesktop',//路由重定向
    meta: {
      title: '首页',
      requireAuth: true
    },
    children: [
      {
        path: '/Workdesktop',
        name: 'Workdesktop',
        component: () => import('../views/WorkDesktop/Workdesktop'),
        meta: {
          title: '工作桌面',
          requireAuth: true,//添加该字段，表示进入路由是否需要登录
        },
      },
      {
        path: '/supervision',
        name: 'supervision',
        component: () => import('../views/supervision/supervision'),
        meta: {
          title: '政治监督',
          requireAuth: true,//添加该字段，表示进入路由是否需要登录
        },
      },
      {
        path: '/cadre',
        name: 'cadre',
        component: () => import('../views/cadre/cadre'),
        meta: {
          title: '党员干部',
          requireAuth: true,//添加该字段，表示进入路由是否需要登录
        },
      },
      {
        path: '/live',
        name: 'live',
        component: () => import('../views/live/live'),
        meta: {
          title: '政治生活',
          requireAuth: true,//添加该字段，表示进入路由是否需要登录
        },
      },
      {
        path: '/report',
        name: 'report',
        component: () => import('../views/report/report'),
        meta: {
          title: '四报告',
          requireAuth: true,//添加该字段，表示进入路由是否需要登录
        },
      },
      {
        path: '/lifewouldbe',
        name: 'lifewouldbe',
        component: () => import('../views/lifewouldbe/lifewouldbe'),
        meta: {
          title: '民主生活会',
          requireAuth: true,//添加该字段，表示进入路由是否需要登录
        },
      },
    ]
  },

]

const router = new VueRouter({
  mode: process.env.VUE_APP_ROUTER_MODE,
  base: process.env.BASE_URL,
  routes
})
// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.matched.length) {//路由是否存在，不存在跳转404
    //我在这里模仿了一个获取用户信息的方法
    let token = window.localStorage.getItem('token');
    if (token) {
      //如果用户信息存在则往下执行。
      next()
    } else {
      //如果用户token不存在则跳转到login页面
      if (to.path === '/login') {
        next()
      } else {
        next('/login')
      }
    }
  } else {
    next('/404')
  }
})


export default router
